import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:study_demo/api/api.dart';
import 'package:study_demo/api/bean.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../util/utils.dart';

class DistributeBoardController extends BaseController {
  LoginUser loginUser = LoginUser();
  final info = ''.obs;
  final area = ''.obs;
  int deptId = 0;
  BoardInfo detail = BoardInfo();
  final areaList = [].obs;
  final areas = [].obs;
  final classList = [].obs;
  int areaId = 0;
  String areaName = '';
  final detailInfo = ''.obs;
  final isDistribute = false.obs;
  int userId = 0;
  String dyPassword = '';

  TextEditingController _userNameEditingController = TextEditingController();

  TextEditingController get userNameEditingController =>
      _userNameEditingController;

  TextEditingController _passwordEditingController = TextEditingController();

  TextEditingController get passwordEditingController =>
      _passwordEditingController;

  TextEditingController _boardCodeEditingController = TextEditingController();

  TextEditingController get boardCodeEditingController =>
      _boardCodeEditingController;

  TextEditingController _areaController = TextEditingController();

  TextEditingController get areaController => _areaController;

  @override
  onInit() {
    super.onInit();
    _passwordEditingController.text = '123456';
    // login();
  }

  getInfo() {
    String userName = _userNameEditingController.text;
    String password = _passwordEditingController.text;

    api.getYzSE(RequestModel(user_info, userInfoInfo(userName, password)),
        success: (json) {
      loginUser = LoginUser.fromJson(json);
      var userId = loginUser.parentid;
      info.value = userId.toString();
      print('userId:$userId');
      loginBackendSystem();
    }, error: (msg) {
      toast(msg);
    });
  }

  login() {
    api.get(RequestModel(login_code, loginInfo('罗彪', '123456'), userId: 0),
        success: (json) {
      dyPassword = json['dypassword'];
      userId = json['userid'];
    });
  }

  loginBackendSystem() async {
    Dio dio = Dio();

    final response = await dio.post(
      'http://dev.izis.cn:8080/yzgoweb/sys/autoLogin/${loginUser.userid}/${loginUser.dypassword}',
      options: Options(
        responseType: ResponseType.json,
      ),
    );

    print('response:$response');

    if (response.statusCode == 200) {
      final responseData = response.data;

      if (responseData['code'] == 0) {
        // 登录成功
        final token = responseData['token'];
        print('token:$token');
        chessList(token);
        getClassList(token);
      }
    }
  }

  var classId = 0;

  chessList(String token) async {
    Dio dio = Dio();
    final response = await dio.get(
      'http://dev.izis.cn:8080/yzgoweb/tclass/list?_search=false&nd=1755507791050&limit=10&page=1&sidx=&order=asc',
      options: Options(
        responseType: ResponseType.json,
        headers: {
          'token': token,
        },
      ),
    );
    print('response:$response');
    // Map<String, dynamic> data = jsonDecode(response.data['page']['list']);

    List<ClassInfo> classList = List<ClassInfo>.from(
      response.data['page']['list'].map(
        (item) => ClassInfo.fromJson(item as Map<String, dynamic>),
      ),
    );
    classList.forEach((it) {
      print('className:${it.teachername}');
      if (it.teachername!.contains(loginUser.realname!)) {
        classId = it.id!;
        print('classId:$classId');
      }
    });
  }

  getClassList(String token) async {
    Dio dio = Dio();
    final response = await dio.get(
      'http://dev.izis.cn:8080/yzgoweb/tclass/classroomlistByDeptId/' +
          info.value,
      options: Options(
        responseType: ResponseType.json,
        headers: {
          'token': token,
        },
      ),
    );
    print('response:${response.data['classroomlist']}');
    var list = List<AreaInfo>.from(response.data['classroomlist']
        .map((e) => AreaInfo.fromJson(e))
        .toList());
    areaList.value = list;

    await Future.delayed(Duration(milliseconds: 300));

    getRoomList(token, classId);
  }

  getRoomList(String token, int id) async {
    Dio dio = Dio();
    final response = await dio.get(
      'http://dev.izis.cn:8080/yzgoweb/tclass/info/' + id.toString(),
      options: Options(
        responseType: ResponseType.json,
        headers: {
          'token': token,
        },
      ),
    );
    print('response:$response');
    var data = response.data;
    int roomId = data['tClass']['roomid'];
    print('roomId:$roomId');
    areaList.forEach((it) {
      // print('it:$it');
      if (it.id == roomId) {
        print('areaName:${it.areaName}');
        area.value = it.areaName;
      }
    });
  }

  copyCode() {
    copyToClipboard(info.value);
    toast('复制成功');
  }

  searchBoard() {
    String boardCode = _boardCodeEditingController.text;
    if (boardCode.isEmpty) {
      toast('棋盘编号不能为空');
      return;
    }
    api.get(RequestModel(board_code_info, boardCodeInfo(boardCode)),
        success: (json) {
      var list = List<BoardInfo>.from(
          json['list'].map((e) => BoardInfo.fromJson(e)).toList());
      if (list.isNotEmpty) {
        deptId = list[0].deptId!;
        boardDetail();
        getAreaInfo(deptId);
      }
    });
  }

  boardDetail() {
    api.get(
        RequestModel(
            board_detail, boardDetailInfo2(_boardCodeEditingController.text)),
        success: (json) {
      print('boardDetail:${detail.areaId}');
      detail = BoardInfo.fromJson(json);
      _areaController.text = detail.areaname ?? '';
      detailInfo.value =
          '设备ID:' + detail.deviceid! + ' 所属部门:' + detail.deptName!;
      if (detail.areaId != 0) {
        isDistribute.value = true;
      }
    });
  }

  getAreaInfo(int deptId) {
    api.get(RequestModel(area_info, areaInfo(deptId)), success: (value) {
      var list =
          List<AreaInfo>.from(value.map((e) => AreaInfo.fromJson(e)).toList());
      areaList.value = list;
      print('areaList:$list');
      areas.clear();
      areaList.forEach((it) {
        print('name:${it.areaName}');
        areaId = it.id;
        areaName = it.areaName;
        areas.add(it.areaName);
      });
    });
  }

  distributeToClassRoom() {
    var info = _areaController.text;
    if (isDistribute.value) {
      areaList.forEach((it) {
        if (it.areaName == info) {
          areaId = it.id;
          areaName = it.areaName;
        }
      });
    } else {
      areaId = 0;
      areaName = '';
    }
    print('areaId:$areaId');
    print('areaName:$areaName');
    detail.areaId = areaId;
    detail.areaname = areaName;
    api.post(
        RequestModel(change_area_info, changeAreaInfo(detail),
            sNum: dyPassword, userId: userId), success: (value) {
      toast('分配成功');
    }, error: (msg) {
      toast(msg);
    });
  }

  enterBackendSystem() {
    launchUrl(Uri.parse(
        "http://dev.izis.cn:8080/yzgoweb/autoLogin.html?userId=${loginUser.userid}&pwd=${loginUser.dypassword}"));
  }

  changeDistribute() {
    isDistribute.value = !isDistribute.value;
  }
}
